import React, {useEffect, useState} from 'react';
import {Image, ScrollView, StyleSheet, Text, TextInput, View} from 'react-native';
import {useNavigation, useRoute} from '@react-navigation/native';
import screen from '../../utils/screen';
import Images from '../../images/images';
import LinkButton from '../../components/linkButton';
import Container from '../../components/Container';
import TouchableView from '../../components/touchableView';
import {useToast} from '../../components/toast/useToast';
import {useDialog} from '../../components/dialog/useDialog';
import {getByteLength} from '../../utils/common';
import _ from 'lodash'

const emotionStrArr = ["[位置]", "[海拔]", "[气压]", "[设备]"]

const TemplateEdit = ()=>{
    const navigation = useNavigation()
    const route = useRoute()
    const toast = useToast()
    const dialog = useDialog()
    const {data,callback} = route.params
    const [message,setMessage] = useState('')
    const [selection,setSelection] = useState(null)


    useEffect(()=>{

        if(data){
            setMessage(data.message)
            navigation.setOptions({
                title:'短信详情',
                headerRight:()=>{
                    return (
                        <TouchableView
                            style={{paddingHorizontal: screen.PIXEL_20}}
                            onPress={deleteMessage}
                        >
                            <Image source={Images.delete}
                                   resizeMode={'contain'}
                                   style={{width:screen.PIXEL_30,height:screen.PIXEL_30}}
                            />
                        </TouchableView>
                    )
                }
            })
        }

    },[])

    const deleteMessage = ()=>{
        dialog.alert({
            title:'删除短信模板？',
            button: [
                {
                    text: '确定',
                    onPress: () => {
                        let obj = {...data,delete:true}
                        callback(obj)
                        navigation.goBack()
                    },
                    pressHide: true,
                    tag: 'confirm',
                    onClose: false
                },
                {
                    text: '取消',
                    onPress: () => {

                    },
                    pressHide: true,
                    tag: 'cancel',
                    onClose: false
                },
            ]
        })

    }

    const saveMessage = ()=>{

        console.log('msglength:',getByteLength(message));
        // console.log('message',message)
        if(!message){
            toast.show('请输入短信模板')
            return
        }
        var regex =new RegExp('\\[[a-zA-Z0-9\\/\\u4e00-\\u9fa5]+\\]','g');
        var regArray = message.match(regex)
        if(regArray && regArray.length){
            let isValidate = true
            for (const reg of regArray) {
                if(emotionStrArr.findIndex(emotionStr=> emotionStr == reg)=== -1){
                    isValidate = false
                    break
                }
            }
            if(!isValidate){
                toast.show('输入有误，请重新输入')
                return
            }
        }

        let obj = {message:message.trim()}
        if(data){
            obj = {...data,message}
        }
        callback(obj)
        navigation.goBack()

    }

    const renderTagItem = (onPress,icon,text,isRight)=>{
        return (
            <TouchableView
                style={[styles.tag,isRight && {marginLeft: screen.PIXEL_30}]}
                onPress={onPress}
            >
                <View style={styles.rowCenter}>
                    <Image source={icon} style={styles.tagImg} resizeMode={'contain'}/>
                    <Text style={styles.tagText}>{text}</Text>
                </View>

                <Image source={Images.add1} style={styles.tagImg} resizeMode={'contain'}/>
            </TouchableView>
        )
    }

    const  insertStr = (source, n, newStr) => {
        return source.slice(0, n) + newStr + source.slice(n)
    }

    const addIcon = (icon)=>{
        if((message + icon).length > 50) return
        let newMsg = message + icon
        if(selection && selection.start === selection.end){
            newMsg = insertStr(message,selection.start,icon)
        }

        setSelection({start:newMsg.length,end:newMsg.length})
        setMessage(newMsg)
    }

    return (
        <Container>
            <ScrollView
                contentContainerStyle={{paddingHorizontal:screen.PIXEL_30,alignItems:'center',paddingTop:screen.PIXEL_40}}
            >
                <View style={styles.inputWrap}>
                    <TextInput

                        multiline={true} value={message} onChangeText={setMessage}
                        placeholder={'请输入模板'} style={styles.input} maxLength={50}
                        onSelectionChange={({nativeEvent: { selection }})=>{
                            // console.log(selection);
                            setSelection(selection)
                        }}
                    />
                    <Text style={styles.numText}>{message.length} / 50</Text>
                </View>

                <View style={styles.tagWrap}>
                    {
                        renderTagItem(()=>{
                            addIcon( '[位置]')
                        },Images.loc_icon,'经纬度')

                    }
                    {
                        renderTagItem(()=>{
                            addIcon( '[气压]' )
                        },Images.pressure,'气压数据',true)
                    }

                </View>

                <View style={[styles.tagWrap,{marginTop:screen.PIXEL_20}]}>
                    {
                        renderTagItem(()=>{
                            addIcon( '[海拔]')
                        },Images.alt_icon,'海拔数据')

                    }
                    {
                        renderTagItem(()=>{
                            addIcon(['[设备]'])
                        },Images.device_icon,'发送设备',true)
                    }

                </View>


            </ScrollView>

            <LinkButton
                style={{marginBottom:screen.PIXEL_120,alignSelf:'center'}}
                title={'保存'}
                onPress={saveMessage}
            />
        </Container>
    )
}
export default TemplateEdit

const styles = StyleSheet.create({
    container:{
        flex: 1
    },
    inputWrap:{
        width:'100%',height:screen.PIXEL_200,backgroundColor:'#fff',
        borderRadius:screen.PIXEL_20,padding:screen.PIXEL_20,marginBottom:screen.PIXEL_30,
    },
    input:{
        flex:1,padding:0,textAlignVertical: 'top'
    },
    numText:{
        textAlign:'right',fontSize:12,color:'#333'
    },
    tagWrap:{
        flexDirection: 'row'
    },
    tag:{
        flex:1,height:screen.PIXEL_90,backgroundColor: '#fff',flexDirection:'row',alignItems:'center'
        ,justifyContent:'space-between', borderRadius: screen.PIXEL_20,paddingHorizontal:screen.PIXEL_30
    },
    rowCenter:{
        flexDirection:'row',alignItems: 'center'
    },
    tagImg:{
        width:screen.PIXEL_30,height:screen.PIXEL_30
    },
    tagText:{
        marginLeft:screen.PIXEL_16,color:'#333',fontSize: screen.PIXEL_30
    }
})
